/*
* import Tr from './trace.js'
*
* // 页面埋点，在页面加载后执行
* // 页面连接中假如 channelId=xxx ，则在埋点中自动获取参数 channelId
* Tr.vt();
*
*
* 事件埋点
* Tr.et('事件名称',参数)
*
* 参数是一个对象
* 比如传入 参数 课程ID
* {
*   classId:111
* }
*
*
*
* */
function getUrlParam (name) {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    } else {
        return null;
    }
}
const ua = window.navigator.userAgent.toLowerCase();
const inIos = ua.match(/(iphone|ipod|ios)/ig);
const inAndroid = ua.match(/(android)/ig);
const inMobile = ua.match(/applewebkit.*mobile.*/ig);
const inWeibo = ua.match(/(weibo)/ig);
const inWechat = ua.match(/(micromessenger)/ig);
const inQQ = ua.match(/(qq(?!browser))/ig);
const inQQBrower = ua.match(/(qqbrowser)/ig);
const inHJQ = ua.match(/(uniapp)/ig) || getUrlParam('hjq') || getUrlParam('uniapp');
const inLeadeon = ua.match(/(leadeon)/ig) || !!getUrlParam('leadeon');
const Ua = {
    ua,
    inIos,
    inAndroid,
    inMobile: inMobile || inIos || inAndroid,
    inWeibo,
    inQQ,
    inWechat,
    inQQBrower,
    inHJQ,
    inLeadeon// 集团掌厅
};
const defaultValue = {
    channelId: ((['inHJQ', 'inLeadeon', 'inWeibo', 'inWechat', 'inQQ']).filter((k) => {
        return Ua[k];
    })).join()
};
const config = {
    project: 'webCastXes'
};
function commonParams () {
    return Object.assign(config.parameters || {}, {
        channelId: getUrlParam('channelId') || config.channelId || defaultValue.channelId || 'HJQCommonChannelId'
    });
}
function isTest () {
    return (location.origin.match(/127\.0\.0\.1/g)
        || location.origin.match(/0\.0\.0\.0/g)
        || location.origin.match(/localhost/g)
        || location.origin.match(/test/g)
        || location.origin.match(/\d+\.\d+\.\d+\.\d+\:\d+/));
}
const SERVERURL = isTest() ? '5' : '6';
function getTime () {
    const now = new Date();
    const year = now.getFullYear().toString();
    const month = now.getMonth() <= 8 ? `0${(now.getMonth() + 1).toString()}` : (now.getMonth() + 1).toString();
    const day = now.getDate() <= 9 ? `0${now.getDate()}` : now.getDate().toString();
    const hours = now.getHours() <= 9 ? `0${now.getHours()}` : now.getHours().toString();
    const minutes = now.getMinutes() <= 9 ? `0${now.getMinutes()}` : now.getMinutes().toString();
    const seconds = now.getSeconds() <= 9 ? `0${now.getSeconds()}` : now.getSeconds().toString();
    const millSeconds = now.getMilliseconds() <= 9 ? `00${now.getMilliseconds()}`
        : now.getMilliseconds() <= 99 ? `0${now.getMilliseconds()}` : now.getMilliseconds().toString();
    return {
        str: year + month + day + hours + minutes + seconds + millSeconds,
        time: now.getTime()
    };
}
const enterTime = getTime().time;
const enterTimeString = getTime().str;
const defaultIdentity = function () {
    return getUrlParam('mobile') || getUrlParam('passId');
};
const getServerUrl = function (n = SERVERURL) {
    const getServerUrlMap = {
        '2': 'https://hsop.komect.com:11444/TRACEProbeService/accept',
        '5': 'https://test.hsop.komect.com:10443/TRACEProbeService/accept',
        '6': 'https://trace.hjq.komect.com/TRACEProbeService/accept'
    };
    return getServerUrlMap[n] || ((n.includes('http') && n) || 'https://trace.hjq.komect.com/TRACEProbeService/accept');
};
const params = {
    '21': {
        '8': [{
            '6': '50D9CFBD-679B-4B44-8FDC-7327B28C24051505204571912',
            '9': enterTimeString
        }]
    },
    '19': {
        '5': window.navigator.userAgent.toLowerCase().match(/(android)/ig) ? '14677915459507539aa11e10150e4b25' : '1467853866494ceb53c83655097037de', // andriodorios
        '32': 'iphone',
        '25': '50D9CFBD-679B-4B44-8FDC-7327B28C2405',
        '33': '19',
        '26': 'unknown',
        '41': '2G/3G/4G',
        '34': 'iOS',
        '27': 'iPhone',
        '42': '4G',
        '35': '9.1',
        '28': 'apple',
        '43': '中国移动',
        '36': 'zh_CN',
        '29': '1.9.0',
        '51': '',
        '44': 'unknown',
        '37': 'zh-Hans-CN',
        '52': '0',
        '45': 'unknown',
        '38': '+8',
        '46': 'unknown',
        '39': '1334*750',
        '31': 0,
        '24': 'unknown'
    }
};
const setTrace = function (isEvent, {
    identity,
    webType = 'H5',
    activityName = '',
    activityDuration,
    activityTime = enterTimeString,
    version,
    session,
    webUrl,
    parameters = {},
    activeCount,
    eventCode = '',
    eventDesc = '',
    serverUrl
} = {}) {
    const defaultParams = commonParams();
    params['19']['51'] = identity;
    params['19']['29'] = version;
    params['19']['52'] = defaultParams.channelId;
    params['21']['15'] ? delete params['21']['15'] : null;
    params['21']['11'] ? delete params['21']['11'] : null;
    if (isEvent) {
        params['21']['15'] = [{
            '6': session,// '6': '50D9CFBD-679B-4B44-8FDC-7327B28C24051505204571912',
            '9': activityTime,
            '16': eventCode, // 事件编码
            '17': eventDesc, // 事件类型
            '50': JSON.stringify(Object.assign(defaultParams, parameters)), // 自定义参数
            '18': 1
        }];
    } else {
        params['21']['11'] = [{
            '1': `${activityDuration}`,
            '4': [
                [
                    activityName,// activityName
                    activityDuration,// activityduration
                    activityTime,// 访问时间
                    webType,// type
                    encodeURIComponent(webUrl), // 页面url
                    JSON.stringify(Object.assign(defaultParams, parameters)),// 自定义参数
                    activeCount
                ]
            ],
            '6': session,
            '9': activityTime
        }];
    }
    if (location.search.includes('tracelog')) {
        alert(`${getServerUrl(serverUrl)}?content=${JSON.stringify(params)}`);
        alert(JSON.stringify(params['19']['29']));
        alert(JSON.stringify(params['21']['11'] ? params['21']['11'][0]['16'] : params['21']['15']));
    }
    const script = document.createElement('script');
    script.src = encodeURI(`${getServerUrl(serverUrl)}?content=${JSON.stringify(params)}`);
    document.getElementsByTagName('body')[0].appendChild(script);
    script.parentNode.removeChild(script);
};
function setTracePro (isEvent, params) {
    params.version = '0.0.0';
    params.session = '0';
    setTrace(isEvent, params);
}
/* 新tace方法 */
const vt = function (pageName = 'Index', parameters = {}) {
    const {
        webUrl = location.href,
        webType = 'H5',
        activeCount = String(enterTime),
        serverUrl = SERVERURL
    } = parameters;
    const identity = parameters.identity = parameters.mobile = (parameters.mobile || config.mobile || parameters.identity || defaultIdentity());
    parameters.webtitle = (parameters.webtitle || document.title || 'HJQCommonTitle');
    setTracePro(false, {
        identity,
        webType,
        activityName: `${config.project ? `${config.project}_` : ''}${pageName}_START`,
        activityDuration: 1,
        activityTime: enterTimeString,
        webUrl,
        parameters,
        activeCount,
        serverUrl
    });
    window.addEventListener('beforeunload', () => {
        const now = (new Date()).getTime();
        const activityDuration = now - enterTime;
        setTracePro(false, {
            identity,
            webType,
            activityName: `${config.project ? `${config.project}_` : ''}${pageName}_UNLOAD`,
            activityDuration,
            activityTime: enterTimeString,
            webUrl,
            parameters,
            activeCount,
            serverUrl
        });
    });
};
const et = function (eventCode, parameters = {}) {
    const {
        serverUrl = SERVERURL,
        eventDesc = eventCode
    } = parameters;
    const identity = parameters.identity = parameters.mobile = (parameters.mobile || config.mobile || parameters.identity || defaultIdentity());
    parameters.webtitle = (parameters.webtitle || document.title || 'HJQCommonTitle');
    setTracePro(true, {
        identity,
        activityTime: enterTimeString,
        eventCode: `${config.project ? `${config.project}_` : ''}${eventCode}`,
        eventDesc,
        parameters,
        serverUrl
    });
};
export default {
    vt,
    et
};
